from fastapi import Request

from app.blog_service.models.blog import BlogVisit


def get_client_ip(request):
    """从请求中获取客户端IP地址"""
    x_forwarded_for = request.headers.get("X-Forwarded-For")
    if x_forwarded_for:
        return x_forwarded_for.split(',')[0]
    return request.client.host


def get_user_agent_info(user_agent: str):
    """解析User-Agent获取操作系统和浏览器信息"""
    # 使用正则表达式进行更精确的解析
    os = "Unknown"
    browser = "Unknown"

    # 操作系统检测
    if "Windows NT" in user_agent:
        os = "Windows"
    elif "Macintosh" in user_agent:
        os = "Mac OS"
    elif "Linux" in user_agent:
        os = "Linux"
    elif "Android" in user_agent:
        os = "Android"
    elif "iPhone" in user_agent or "iPad" in user_agent:
        os = "iOS"

    # 浏览器检测
    if "Chrome" in user_agent:
        browser = "Chrome"
    elif "Firefox" in user_agent:
        browser = "Firefox"
    elif "Safari" in user_agent and "Chrome" not in user_agent:
        browser = "Safari"
    elif "Edge" in user_agent:
        browser = "Edge"
    elif "MSIE" in user_agent or "Trident" in user_agent:
        browser = "Internet Explorer"

    return os, browser


def get_blog_visit(request: Request, blog_id: int) -> BlogVisit:
    ip = get_client_ip(request)
    user_agent = request.headers.get("User-Agent", "")
    os, browser = get_user_agent_info(user_agent)

    return BlogVisit(
        ip=ip,
        os=os,
        browser=browser,
        uri=request.url.path,
        blog_id=blog_id
    )
